package com.api.workflow.web;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.workflow.util.CreateWorkflowDetailUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import weaver.common.util.string.StringUtil;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.workflow.webservices.WorkflowRequestInfo;
import weaver.workflow.webservices.WorkflowServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/*
 * mm调OA的接口
 * */
@Path("/yn/mm/oa")
public class YNMMOAController extends BaseBean {
    public static void main(String[] args) {

    }
    /**
     * QMI001检测缺陷记录同步至OA
     * 对应流程上的  （质量管理） 生产不合格评审单流程   采购不合格评审单流程
     * 进行创建流程
     *
     * @param request
     * @param response
     * @param Data
     * @return
     */
    @POST
    @Path("/QMI001")
    @Produces(MediaType.APPLICATION_JSON)
    public String QMI001(@Context HttpServletRequest request, @Context HttpServletResponse response, @Valid @RequestBody String Data) {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        BaseBean baseBean = new BaseBean();
        RecordSet recordSet = new RecordSet();
        RecordSet recordSet1 = new RecordSet();
        String workflowId = null;
        String requestName = null;
        String mainFields = null;
        String workflowDetail = null;
        writeLog("=========QMI001====Data:" + Data);
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> bodyMap = objectMapper.readValue(Data, Map.class);
            if (bodyMap.get("QMART") == null) {
                objectObjectHashMap.put("status", "error");
                objectObjectHashMap.put("message", "通知单类型不能为空");
                return JSONObject.toJSONString(objectObjectHashMap);
            }
            String QMART = bodyMap.get("QMART").toString();
            //明细1
            //workflowDetail = JSONObject.toJSONString(bodyMap.get("DATA"));
            //bodyMap.remove("DATA");
            //主表
            //mainFields = JSONObject.toJSONString(bodyMap);
            JSONArray jsonArray = new JSONArray();
            Map<String, Object> resultObject = new HashMap<>();
            resultObject.put("tzdh", Util.null2String(bodyMap.get("QMNUM")) );
            resultObject.put("gc", Util.null2String(bodyMap.get("MAWERK")));
            resultObject.put("tzdlx", Util.null2String(bodyMap.get("QMART")));
            resultObject.put("tzddwb", Util.null2String(bodyMap.get("QMARTX")));
            resultObject.put("wlbm", Util.null2String(bodyMap.get("MATNR")));
            resultObject.put("wlms", Util.null2String(bodyMap.get("MAKTX")));
            resultObject.put("jyp", Util.null2String(bodyMap.get("PRUEFLOS")));
            resultObject.put("jypdwb", Util.null2String(bodyMap.get("KTEXTLOS")));
            resultObject.put("dhsl", Util.null2String(bodyMap.get("LOSMENGE")));
            resultObject.put("pchm", Util.null2String(bodyMap.get("CHARG")));
            resultObject.put("cysl", Util.null2String(bodyMap.get("GESSTICHPR")));
            resultObject.put("cgddhE", Util.null2String(bodyMap.get("BELN")));
            resultObject.put("gysdm", Util.null2String(bodyMap.get("SELLIFNR")));
            resultObject.put("gysms", Util.null2String(bodyMap.get("NAME1")));
            resultObject.put("khdm", Util.null2String(bodyMap.get("SELKUNNR")));
            resultObject.put("khms", Util.null2String(bodyMap.get("NAME1_KUNNR")));
            resultObject.put("xsddh", Util.null2String(bodyMap.get("LS_KDAUF")));
            resultObject.put("LAGORTCHRG", Util.null2String(bodyMap.get("LAGORTCHRG")));
            resultObject.put("kcddms", Util.null2String(bodyMap.get("LGOBE")));
            resultObject.put("scdd", Util.null2String(bodyMap.get("FERTAUFNR")));
            resultObject.put("wlz", Util.null2String(bodyMap.get("MATKL")));
            resultObject.put("wlzms", Util.null2String(bodyMap.get("WGBEZ")));
            resultObject.put("cgz", Util.null2String(bodyMap.get("BKGRP")));
            resultObject.put("cgzms", Util.null2String(bodyMap.get("EKOTX")));
            resultObject.put("sqrq", Util.null2String(bodyMap.get("ERDAT")));
            //增加字段
            resultObject.put("ZLIFNR", Util.null2String(bodyMap.get("ZLIFNR")));//厂家
            resultObject.put("KTEXT", Util.null2String(bodyMap.get("KTEXT")));//车间
            baseBean.writeLog("lyh==QMI001===========resultObject" + resultObject.toString());
            Object data = bodyMap.get("DATA");
            baseBean.writeLog("lyh==QMI001===========data" +JSONObject.toJSONString(data));
            JSONArray detailObject = JSONObject.parseArray(JSONObject.toJSONString(data));


            for (int i = 0; i < detailObject.size(); i++) {
                JSONObject jsonObject1 = detailObject.getJSONObject(i);
                Map<String, Object> insetMap = new HashMap<>();
                String kurztext = Util.null2String(jsonObject1.get("PRUEFER"));
                recordSet.executeQuery("select * from hrmResource where lastname=?",kurztext);

                String id="";
                while (recordSet.next()){
                    id = Util.null2String(recordSet.getString("id"));
                    String departmentid = Util.null2String(recordSet.getString("departmentid"));
                    String subcompanyid1 = Util.null2String(recordSet.getString("subcompanyid1"));
                    String jobtitle = Util.null2String(recordSet.getString("jobtitle"));
                    String workcode = Util.null2String(recordSet.getString("workcode"));
                    String gsdm11="";
                    if(!StringUtil.isNullOrEmpty(subcompanyid1)){
                        recordSet1.executeQuery("select * from uf_gsdykzfwb where gsmc=?",subcompanyid1);
                        recordSet1.next();
                        gsdm11 = Util.null2String(recordSet1.getString("gsdm"));
                    }
                    resultObject.put("sqr", id);
                    resultObject.put("sqbm", departmentid);
                    resultObject.put("sqdw", subcompanyid1);
                    resultObject.put("sqrgw",jobtitle );
                    resultObject.put("sqrgh",workcode );
                    resultObject.put("gsdm",gsdm11 );
                    baseBean.writeLog("sqrsqrsqrsqr"+id);
                    baseBean.writeLog("sqbmsqbmsqbmsqbm"+departmentid);
                    baseBean.writeLog("sqdwsqdwsqdwsqdwsqdw"+subcompanyid1);
                    baseBean.writeLog("sqrgwsqrgwsqrgwsqrgwsqrgw"+jobtitle);
                    baseBean.writeLog("sqrghsqrghsqrghsqrghsqrgh"+workcode);
                    baseBean.writeLog("gsdm11gsdm11"+gsdm11);
                }
                insetMap.put("jyxm", Util.null2String(jsonObject1.get("KURZTEXT")));
                insetMap.put("jybz", Util.null2String(jsonObject1.get("ZQMXB")));
                insetMap.put("jyjg", Util.null2String(jsonObject1.get("ZQMJG")));
                insetMap.put("jyjl", Util.null2String(jsonObject1.get("ZQMJL")));
                insetMap.put("jyy", id);
                insetMap.put("jyms", Util.null2String(jsonObject1.get("PRUEFBEMKT")));
                insetMap.put("qxdj", Util.null2String(jsonObject1.get("FEQKLAS")));
                insetMap.put("bzxx", Util.null2String(jsonObject1.get("ZBZ")));
                jsonArray.add(insetMap);
            }
            baseBean.writeLog("lyh==QMI001===========jsonArray" + jsonArray.toString());

            //这里处理是那个流程的数据
            if (QMART.equals("Z1")) {
                //采购
                workflowId = getPropValue("YNSap", "QMI001CGWorkflowId");
                requestName = "采购不合格评审单"+Util.null2String(bodyMap.get("MAKTX"))+getCurrentDate();
            } else if (QMART.equals("Z2")) {
                // 生产
                workflowId = getPropValue("YNSap", "QMI001SCWorkflowId");
                requestName = "生产不合格评审单"+Util.null2String(bodyMap.get("MAKTX"))+getCurrentDate();
            } else {
                objectObjectHashMap.put("status", "error");
                objectObjectHashMap.put("message", "通知单类型错误应为Z1,Z2");
                return JSONObject.toJSONString(objectObjectHashMap);
            }
            baseBean.writeLog("lyh==QMI001===========resultObjectresultObjectresultObject" + resultObject.toString());
            mainFields=JSONObject.toJSONString(resultObject);
            workflowDetail=JSONObject.toJSONString(jsonArray);
            writeLog("=========QMI001=====requestName:" +requestName);
            writeLog("=========QMI001=====workflowId:" +workflowId);
            writeLog("=========QMI001=====mainFields:" +mainFields);
            writeLog("=========QMI001=====workflowDetail:" +workflowDetail);
            String requestid = CreateWorkflowDetailUtil.createWorkflowDetail(requestName, workflowId, "1",mainFields, workflowDetail);
            String submit = Submit(requestid, "1");
            writeLog("=========QMI001=====requestid:" + requestid);
            writeLog("=========QMI001=====submit:" + submit);
            if("success".equals(submit)) {
                submit = "ok";
                writeLog("=========QMI001=====submit msg 流程提交成功:" + submit);
            }else if ("failed".equals(submit)){
                submit = "error";
                writeLog("=========QMI001=====submit msg 流程提交失败:" + submit);
            }else {
                writeLog("=========QMI001=====submit errmsg:" + submit);
            }
            objectObjectHashMap.put("status", submit);
        } catch (Exception e) {
            objectObjectHashMap.put("status", "error");
            objectObjectHashMap.put("message", "系统内部错误");
            writeLog("========QMI001=====error:" + e.toString());
            return JSONObject.toJSONString(objectObjectHashMap);
        }
        return JSONObject.toJSONString(objectObjectHashMap);
    }
    // 获取当前日期，格式为 yyyy-MM-dd
    public static String getCurrentDate() {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 定义格式化模式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 格式化当前日期并返回
        return currentDate.format(formatter);
    }

    /**
     * 提交流程
     *
     * @param requestId 流程号
     * @param userId    用户id
     * @return
     */
    public String Submit(String requestId, String userId) {
        WorkflowServiceImpl ws = new WorkflowServiceImpl();
        WorkflowRequestInfo wri = new WorkflowRequestInfo();
        String result = ws.submitWorkflowRequest(wri,
                Integer.parseInt(requestId), Integer.parseInt(userId), "submit",
                "自动提交");
        return result;
    }

    @GET
    @Path("/YNFII009Task")
    @Produces(MediaType.APPLICATION_JSON)
    public String YNFII009Task(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        try{
            YNFII009Task ynfii009Task = new YNFII009Task();
            ynfii009Task.execute();
            objectObjectHashMap.put("status","success");
        }catch (Exception e){
            objectObjectHashMap.put("status","error");
        }
        return JSONObject.toJSONString(objectObjectHashMap);
    }

    @GET
    @Path("/YNFII010Task")
    @Produces(MediaType.APPLICATION_JSON)
    public String YNFII010Task(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        try{
            YNFII010Task ynfii010Task = new YNFII010Task();
            ynfii010Task.execute();
            objectObjectHashMap.put("status","success");
        }catch (Exception e){
            objectObjectHashMap.put("status","error");
        }
        return JSONObject.toJSONString(objectObjectHashMap);
    }

}
